package com.tinyideatech.admin.controller.mall;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tinyideatech.common.core.controller.BaseController;
import com.tinyideatech.common.core.entity.ApiResult;
import com.tinyideatech.common.core.entity.PageResult;
import com.tinyideatech.common.core.text.Convert;
import com.tinyideatech.common.utils.StringUtils;
import com.tinyideatech.framework.utils.ExcelUtils;
import com.tinyideatech.framework.utils.FtpUtil;
import com.tinyideatech.system.entity.MallOrder;
import com.tinyideatech.system.entity.MallOrderItem;
import com.tinyideatech.system.service.IMallOrderItemService;
import com.tinyideatech.system.service.IMallOrderService;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author zhangy-5
 * @date 2019-08-26
 */

@Controller
@RequestMapping("/mall/order")
public class MallOrderController extends BaseController {

    @Autowired
    private IMallOrderService mallOrderService;
    @Autowired
    private IMallOrderItemService orderItemService;


    @GetMapping()
    public String list() {
        return "mall/order/list";
    }

    @GetMapping("/add")
    public String add() {
        return "mall/order/add";
    }

    @GetMapping("/detail/{id}")
    public String mallOrderEdit(
            @PathVariable("id") Long id,
            ModelMap map
    ) {
        MallOrder order = mallOrderService.getById(id);
        List<MallOrderItem> orderItems = orderItemService.list(new QueryWrapper<MallOrderItem>().eq("order_id", order.getOrderId()));
        map.addAttribute("order", order);
        map.addAttribute("orderItems", orderItems);
        return "mall/order/detail";
    }

    @ResponseBody
    @PostMapping("/list")
    public PageResult list(
            MallOrder order,
            @RequestParam(required = false, defaultValue = "") Date startTime,
            @RequestParam(required = false, defaultValue = "") Date endTime
    ) {
        QueryWrapper<MallOrder> qw = new QueryWrapper<>();

        if (startTime != null) {
            qw.ge("payment_time", startTime);
        }
        if (endTime != null) {
            qw.le("payment_time", endTime);
        }
        if (StringUtils.isNotEmpty(order.getPaymentResult())) {
            qw.eq("payment_result", order.getPaymentResult());
        }
        if (StringUtils.isNotEmpty(order.getUsername())) {
            qw.like("username", order.getUsername());
        }
        IPage<MallOrder> page = startPage();
        IPage<MallOrder> orderIPage = mallOrderService.page(page, qw);
        return page(orderIPage);
    }

    @ResponseBody
    @PostMapping("/save")
    public ApiResult save(
            MallOrder sysRole
    ) {
        mallOrderService.saveOrUpdate(sysRole);
        return success();
    }

    @ResponseBody
    @PostMapping("/remove")
    public ApiResult remove(
            String ids
    ) {
        Long[] mallOrderIds = Convert.toLongArray(ids);
        mallOrderService.removeByIds(Arrays.asList(mallOrderIds));
        return success();
    }

    @PostMapping("/changeStatus")
    @ResponseBody
    public ApiResult changeStatus(MallOrder mallOrder) {
        mallOrderService.changeStatus(mallOrder);
        return success();
    }

    @ResponseBody
    @PostMapping("/upload")
    public ApiResult upload(
            MultipartFile file
    ) {
        String fileName = System.currentTimeMillis() + file.getOriginalFilename();
        try {
            FtpUtil.uploadFileToFtp("image", "model/" + fileName, file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return success("model/" + fileName);
    }


    @ResponseBody
    @PostMapping("/consume")
    public ApiResult consume(
    ) {
        return success(mallOrderService.consumeAll());
    }


    @ResponseBody
    @GetMapping("/select")
    public ApiResult select(
            @RequestParam int id
    ) {
        if (id == 1) {
            return success(mallOrderService.select().get("adas"));
        } else if (id == 2) {
            return success(mallOrderService.select().get("model"));
        }
        return success(mallOrderService.select().get("sum"));
    }

    @ResponseBody
    @GetMapping("/increase")
    public ApiResult increase(
            @RequestParam int id
    ) {
        if (id == 1) {
            return success(mallOrderService.increase().get("adas"));
        } else if (id == 2) {
            return success(mallOrderService.increase().get("model"));
        }
        return ApiResult.warn("please offer correct params");
    }

    @ResponseBody
    @GetMapping("/sum")
    public ApiResult quantity(
    ) {
        return success(mallOrderService.sum());
    }

    @ResponseBody
    @GetMapping("/week")
    public ApiResult week(
            @RequestParam int id
    ) {
        if (id == 1) {
            return success(mallOrderService.countWeek().get("adas"));
        } else if (id == 2) {
            return success(mallOrderService.countWeek().get("model"));
        }
        return ApiResult.warn("please offer correct params");
    }

    /**
     * Excel下载
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "导出订单Excel")
    @GetMapping("/export/order")
    public void orderExcel(HttpServletResponse response) throws Exception {
        XSSFWorkbook wb = mallOrderService.downloadRecorder();
        String fileName = "MallOrder报表.xlsx";
        ExcelUtils.init(fileName, response, wb);
    }
}

